<template>
  <div class="ValidCode disabled-select" style="width: 100%; height: 100%" @click="refreshCode">
    <!-- 使用v-for循环生成验证码的每一个字符 -->
    <span v-for="(item, index) in codeList" :key="index" :style="getStyle(item)">{{ item.code }}</span>
  </div>
</template>


<script>
export default {
  name: "validCode",

  data() {
    return {
      length: 4, // 验证码长度
      codeList: [], // 存储验证码字符的数组
    }
  },

  mounted() {
    this.createCode() // 组件挂载后立即生成验证码
  },

  methods: {
    // 刷新验证码
    refreshCode() {
      this.createCode()
    },

    // 生成验证码
    createCode() {
      let len = this.length,
          codeList = [],
          chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz0123456789',
          charsLen = chars.length;

      // 循环生成验证码的每一个字符
      for (let i = 0; i < len; i++) {
        let rgb = [Math.round(Math.random() * 220), Math.round(Math.random() * 240), Math.round(Math.random() * 200)];
        codeList.push({
          code: chars.charAt(Math.floor(Math.random() * charsLen)), // 随机字符
          color: `rgb(${rgb})`, // 随机颜色
          padding: `${[Math.floor(Math.random() * 10)]}px`, // 随机内边距
          transform: `rotate(${Math.floor(Math.random() * 90) - Math.floor(Math.random() * 45)}deg)` // 随机旋转角度
        });
      }

      // 更新验证码数组
      this.codeList = codeList;
      // 将当前数据派发出去
      this.$emit('update:value', codeList.map(item => item.code).join(''));},

    // 获取字符样式
    getStyle(data) {
      return `color: ${data.color}; font-size: 18px; padding: ${data.padding}; transform: ${data.transform}`;
    }
  }
}
</script>


<style>
.ValidCode {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.ValidCode span {
  display: inline-block;
  font-size: 18px;
}
</style>
